I use the following code to do the pipe program such as: ls | wc -w for only one "|", but if there are more "|", i do not know how to deal with it
Code:
void pipeProcess(char *args1[], char *args2[]) {
int thepipe[2], pid;
if(pipe(thepipe) == -1)
oops("Can not get a pipe", 1);
/* Create a new process */
if((pid = fork()) == -1)
oops("Can not fork", 2);
if(pid >0) {/* This is parent process */
close(thepipe[1]); /* parent does not write to pipe */
if(dup2(thepipe[0], 0) == -1) /* let parent read interface attaches to stdin */
oops("Could not redirect stdin", 3);
close(thepipe[0]); /* close thepipe[0] interface because it has attached to stdin */
execvp(args2[0], args2);
oops(*args2, 4);
}
/* Child process executes av[1] and writesinto pipe */
close(thepipe[0]); /* Child does not read from pipe */
if(dup2(thepipe[1], 1) == -1)
oops("Could not redirect stdout", 4);
close(thepipe[1]);
execvp(args1[0], args1);
oops(*args1, 5);
}